package com.gitee.dolt.security;

import com.gitee.dolt.cache.repository.CacheOps;
import com.gitee.dolt.security.aspect.UriSecurityPreAuthAspect;
import com.gitee.dolt.security.aspect.VerifyAuthFunction;
import com.gitee.dolt.security.properties.SecurityProperties;
import com.gitee.dolt.security.token.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 权限认证配置类
 *
 * @author LYH
 */
@Order
@RequiredArgsConstructor
@EnableConfigurationProperties({SecurityProperties.class})
public class SecurityAutoConfiguration implements WebMvcConfigurer {
    private final SecurityProperties securityProperties;
    @Value("${spring.profiles.active:dev}")
    protected String profiles;

    @Bean
    @ConditionalOnProperty(prefix = SecurityProperties.PREFIX + ".permission", name = "enabled", havingValue = "true", matchIfMissing = true)
    public UriSecurityPreAuthAspect uriSecurityPreAuthAspect(VerifyAuthFunction verifyAuthFunction) {
        return new UriSecurityPreAuthAspect(verifyAuthFunction);
    }

    @Bean
    @ConditionalOnMissingBean(VerifyAuthFunction.class)
    public VerifyAuthFunction verifyAuthFunction() {
        return new VerifyAuthFunction(securityProperties);
    }

    @Bean
    public TokenProvider tokenProvider(SecurityProperties securityProperties, CacheOps cacheOps,
                                       @Autowired(required = false) List<TokenClaimsIntervention> tokenClaimsInterventions) {
        return new TokenProvider(securityProperties, cacheOps, tokenClaimsInterventions);
    }

    @Bean
    @ConditionalOnProperty(prefix = SecurityProperties.PREFIX + ".jwt", name = "enabled", havingValue = "true", matchIfMissing = true)
    public TokenWebMvcConfigurer tokenWebMvcConfigurer(TokenProvider tokenProvider,
                                                       @Autowired(required = false) List<TokenHandlerIntervention> tokenHandlerInterventions) {
        return new TokenWebMvcConfigurer(new TokenHandlerInterceptor(profiles, tokenProvider, tokenHandlerInterventions, securityProperties));
    }


}
